package win.bitterwine.redis;


import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author 创建人：wangqingyu
 * @version 创建于：2017年2月16日 下午4:43:29
 */
public class JedisPoolUtil {
	private static volatile JedisPool jedisPool = null;
	
	private JedisPoolUtil (){}
	
	public static JedisPool getJedisPoolInstance(){
		if(jedisPool == null){
			synchronized (JedisPoolUtil.class) {
				if(jedisPool == null){
					GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
					poolConfig.setMaxTotal(20);
					poolConfig.setMaxIdle(10);
					poolConfig.setMaxWaitMillis(10*1000);
					//如果连接不上会跑异常(可以设置从机的地址)
					jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379);
				}
			}
		}
		return jedisPool;
	}
	
	/**
	 * 释放
	 * @author 创建人：wangqingyu
	 * @param jedisPool
	 * @param jedis
	 */
	public static void release(JedisPool jedisPool,Jedis jedis){
		if(jedis != null){
			jedisPool.returnResourceObject(jedis);
		}
	}
	
	
	public static void main(String[] args) {
		JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance();
		JedisPool jedisPool2 = JedisPoolUtil.getJedisPoolInstance();
		
		Jedis jedis1 = jedisPool.getResource();
		Jedis jedis2 = jedisPool.getResource();
		
		System.out.println(jedis1 == jedis2);  //false
		
		//System.out.println(jedisPool == jedisPool2);   //true
		
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
//			jedis.set("k88", "v88");
//			System.out.println(jedis.ping());
			System.out.println(jedis.hgetAll("module_1"));
			System.out.println(jedis.hgetAll("module_2"));
			System.out.println(jedis.hgetAll("module_3"));
			System.out.println(jedis.hgetAll("module_4"));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			JedisPoolUtil.release(jedisPool, jedis);
		}
		
		
	}
}
